$(function(){
    var username = getCookie('username')
    if(!username){
        layer.msg('请先登录',{
            icon:2,
            time:2300
        },function(){
            localStorage.setItem('url',location.href)
            location.href = "login.html"
        })
    }
    //获取本地存储中的数据
    var data = localStorage.getItem('data')
    // console.log(data)
    //判断是否获取到数据
    if(!data){
        $(".cart-big").empty()
        // console.log($(".cart-big"))  
        $(".cart-big").html(`
            <div class="jumbotron" style="height:400px;background:#F7F7F7;">
                <img src="./images/cart.png" style="float:left; margin-left:150px;" >
                <div class="jumu" style="float:right;margin-right:150px;margin-top:30px;">
                    <h1>购物车空空如也！</h1>
                    <p>赶快去首页挑选商品吧！</p>
                    <p><a class="btn btn-primary btn-lg" href="xiaomi.html" role="button">立即选购</a></p> 
                </div>
            </div>
        `)
    }else{
        //判断是否有当前这个用户的数据
        var arr = JSON.parse(data).filter(item=>item.username === username)
        if(arr.length){
            var ids = arr.map(item=>item.goodsid).join()
            var loadindex = layer.load(0,{
                shade:[0.3,'skyblue']
            })
            $.get('php/Shopping_Cart.php',{ids},res=>{
                // console.log(res)
                var {meta:{status,msg},data} = res
                var str = ''
                data.forEach(item => {
                    var number = arr.find(v=>v.goodsid === item.id).number
                    str += `
                        <div class="item-box">
                            <div class="item-check">
                                <input type="checkbox" checked name="selectone">
                            </div>
                            <div class="item-img">
                                <a href="details.html?id=${item.id}">
                                <img src="${item.imgpath}" width="90" height="90"></a>
                            </div>
                            <div class="item-name">${item.name}</div>
                            <div class="item-price"><span>${item.price}</span>元</div>
                            <div class="item-num">
                                <button class="reduce">-</button>
                                    <input type="number" checked value="${number}" min=1>
                                <button class="add">+</button>
                            </div>
                            <div class="item-total"><span>${item.price * number}</span>元</div>
                            <div class="item-handle" data-id="${item.id}">
                                <a href="javascript:;" class="btn removecart btn-danger">删除商品</a>
                            </div>
                        </div>
                    `
                })
                $('.cart-head').after(str)
                layer.close(loadindex)
                //调用购物车的功能函数
                selectAll()
                selectOne()
                numAdd()
                numReduce()
                subtotal()
                priceTotal()
                deleteItem()
            },'json')
        }else{
            $(".cart-big").empty()
            $(".cart-big").html(`
                <div class="jumbotron" style="height:400px;background:#F7F7F7;">
                    <img src="./images/cart.png" style="float:left; margin-left:150px;" >
                    <div class="jumu" style="float:right;margin-right:150px;margin-top:30px;">
                        <h1>购物车空空如也！</h1>
                        <p>赶快去首页挑选商品吧！</p>
                        <p><a class="btn btn-primary btn-lg" href="xiaomi.html" role="button">立即选购</a></p> 
                    </div>
                </div>
            `)
        }
    }

    //全选功能
    function selectAll(){
        $('[name="selectAll"]').click(function(){
            $('[name="selectone"]').prop('checked',$(this).prop('checked'))
            $('[name="selectAll"]').prop('checked',$(this).prop('checked'))
            priceTotal()
        })
    }

    //单选功能
    function selectOne(){
        $('[name="selectone"]').click(function(){
            var arr = Array.prototype.slice.call($('[name="selectone"]'))
            var bool = arr.every(item=>item.checked)
            $('[name="selectAll"]').prop('checked',bool)
            priceTotal()
        })
    }

    //商品数量加功能
    function numAdd(){
        $(".item-num .add").click(function(){
            var number = $(this).prev().val() - 0
            number++
            $(this).prev().val(number)
            //修改本地存储中的数据
            var data = localStorage.getItem('data')
            data = JSON.parse(data)
            var id = $(this).parent().siblings().last().attr('data-id')
            var obj = data.find(item=>item.goodsid === id && item.username === username)
            obj.number++
            localStorage.setItem('data',JSON.stringify(data))
            subtotal()
            priceTotal()
        })
    }

    //商品数量减功能
    function numReduce(){
        $(".item-num .reduce").click(function(){
            var number = $(this).next().val() - 0
            number--
            $(this).next().val(number)
            //修改本地存储中的数据
            var data = localStorage.getItem('data')
            data = JSON.parse(data)
            var id = $(this).parent().siblings().last().attr('data-id')
            var obj = data.find(item=>item.goodsid === id && item.username === username)
            obj.number--
            localStorage.setItem('data',JSON.stringify(data))
            subtotal()
            priceTotal()
        })
    }

    //计算小计
    function subtotal(){
        $('.item-num input').each(function(i,v){
            var num = $(v).val() * $(v).parent().prev().find('span').text()
            $(v).parent().next().find('span').text(num)
        })
    }

    //总数量总价格
    function priceTotal(){
        var totalprice = 0
        var totalnum = 0
        $('[name="selectone"]:checked').each(function(i,v){
            totalprice += ($(this).parent().siblings('.item-total').find('span').text() - 0)
            totalnum += ($(this).parent().siblings('.item-num').find('input').val() - 0)
        })
        // console.log(totalnum,totalprice)
        $('.shop-total').find('span').text(totalnum)
        $('.price-total').find('span').text(totalprice)
    }

    //删除商品
    function deleteItem(){
        $('.removecart').click(function(){
            layer.confirm('您确定要删除吗？', {
                btn: ['确定','取消'] 
            }, ()=>{
                $(this).parent().parent().remove()
                subtotal()
                priceTotal()
                //删除本地存储中的该数据
                var data = localStorage.getItem('data')
                data = JSON.parse(data)
                var id = $(this).parent().attr('data-id')
                var index = data.findIndex(item=>item.goodsid === id && item.username === username)
                data.splice(index,1)
                localStorage.setItem('data',JSON.stringify(data))  
                layer.msg('删除成功', {
                    icon: 1,
                    time:2300
                });
            }, function(){
                layer.msg('取消成功', {
                time: 2300, 
                icon:1
            });
            });
        })
    }

    //为你推荐请求数据
    var ids = 10
    var flag = true
    var loadindex = layer.load(0, {
        shade: [0.3, 'skyblue']
    })
    //发送Ajax封装函数
    function loadHtml() {
        if(!flag){
            return false
        }
        flag = false
        $.get('php/recommend.php',{
            ids,
            _: +new Date()
        }, res => {
            // console.log(res)
            var {meta:{status,msg},data} = res
            if(status === 1){
                var str = ''
                //for循环创建li
                for (var i = 0; i < data.length; i++) {
                   str += `
                        <a href='details.html?id=${data[i].id}'><li>
                            <img src="${data[i].image}" class="recommend-pic" height="140" width="${data[i].image.width * 140 / data[i].image.height}">
                            <h5 class="recommend-type">${data[i].name}</h5>
                            <div class="recommend-price"><span>${data[i].price}</span>元</div>
                            <p class="recommend-comments">${data[i].comment}人好评</p>
                        </li></a>
                    `
                    $('.recommend').html(str)
                }
            }
            //加载好数据之后关闭弹出层
            layer.close(loadindex)
            flag = true
            ids += 10
        }, 'json')
    }
    loadHtml()
    
    //监听滚动条事件
    $(window).scroll(function () {
        var t = document.body.scrollTop || document.documentElement.scrollTop
        if(t -100 + innerHeight > $(".main-top").innerHeight() + $(".recommend-big").innerHeight()){
            loadHtml()
        }
    })

    //去结算
    $(".apply").click(function(){
        layer.open({
        type: 1,
        skin: 'layui-layer-rim', 
        area: ['420px', '300px'], //宽高
        content: '<span style="margin-left:20px;margin-right:20px;font-size:23px;color:#424242;">扫码支付</span><img src="./images/myf.jpg"style=" margin-top:20px;" width="200" height="200">'
      });
    })
    
})